from myro import *

shortestDist = 0
shortestPath = []

def genPerms():
    global shortestDist
    global shortestPath
    shortestDist = 0
    shortestPath = []
    def getDist():
        #Opens the file with the distance information
        f = open("Large\Labeled Table.txt", "r")
        #Reads one line of the file and stores it into line
        line = f.readline()
        #returns the items in line into an array
        bldgOrder = line.split()
        #displays the items in bldgOrder
        #print bldgOrder
        # Loops through the length of building order
        for i in range(len(bldgOrder)):
            #Reads the next line of code
            line = f.readline()
            #print line
            distances = line.split()
            rowStart = distances[0]
            #Creates a new entry in the dictionary
            distList[rowStart] = {}
            #Deletes the first distance which is the building name. This is to map correctly.
            del(distances[0])
            for j in range(len(distances)):
                distList[rowStart][bldgOrder[j]] = int(distances[j])
        for k in range(len(bldgOrder)):
            0
            #print bldgOrder[k]
            #print distList[bldgOrder[k]]

    def perms(fullPath, togo):
        togolen = len(togo)
        currelem = len(fullPath)
        if(togolen == 0):
            #print fullPath
            checkDist(fullPath)
            0
        else:
            for i in range(togolen):
                #print togo[i]
                perms(fullPath + [togo[i]], togo[0:i] + togo[i+1:togolen+1])

    def checkDist(fullPath):
        global shortestDist
        global shortestPath
        #print fullPath[0]
        totalTime = distList['OM'][fullPath[0][0]]
        for i in range(len(fullPath) - 1):
            totalTime += distList[fullPath[i][1]][fullPath[i + 1][0]]
        totalTime += distList[fullPath[len(fullPath)-1][1]]['OM']
        if(shortestDist == 0):
            shortestDist = totalTime
            shortestPath = fullPath
        elif(totalTime < shortestDist):
            shortestDist = totalTime
            shortestPath = fullPath
            #print shortestDist
            #print shortestPath
        
    #dictionary of distances
    distList = {}
    #fill the dictionary of distances
    getDist()
    #deliveries array
    deliveries = []
    #get deliveries from file
    fname = raw_input("Whcich file would you like to open? ")
    dels = open('Large\\' + fname)
    delItem = dels.readline().rstrip()
    while(delItem != ""):
        delItemList = delItem.split(" ")
        deliveries.append(delItemList)
        delItem = dels.readline().rstrip()
    shortestDist
    shortestPath
    #gen perms
    start = currentTime()
    perms([], deliveries)
    end = currentTime()
    print "it took ", (end - start), " seconds"
    print shortestPath
    print shortestDist
